package com.lewis.core.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

@SuppressWarnings("rawtypes")
public class IniUtil {

	/**
	 * 存放所有的节（section）对应的参数（properties）：键（key）、值（value）
	 */
	public static final HashMap sections = new HashMap();

	private static Properties current;

	/**
	 * 构造函数
	 * @param filename
	 * @throws IOException
	 */
	public static boolean init(String filename) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(filename));
			// 读取文件
			read(reader);
			// 关闭流
			reader.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	/**
	 * 读取文件
	 * @param reader
	 * @throws IOException
	 */
	private static void read(BufferedReader reader) throws IOException {
		String line;
		while ((line = reader.readLine()) != null) {
			parseLine(line);
		}
	}

	/**
	 * 解析配置文件行
	 * @param line
	 */
	@SuppressWarnings("unchecked")
	private static void parseLine(String line) {
		line = line.trim();
		if (line.matches("\\[.*\\]")) {
			// 当前节
			String currentSection = line.replaceFirst("\\[(.*)\\]", "$1");
			current = new Properties();
			sections.put(currentSection, current);
		} else if (line.matches(".*=.*")) {
			if (current != null) {
				int i = line.indexOf('=');
				String name = line.substring(0, i);
				String value = line.substring(i + 1);
				current.setProperty(name, value);
			}
		}
	}
	/**
	 * 获取值
	 * @param section
	 * @param name
	 * @return
	 */
	public static String getValue(String section, String name) {
		Properties p = (Properties) sections.get(section);
		if (p == null) {
			return null;
		}
		return p.getProperty(name);
	}
	/**
	 * 是否包含key
	 * @param section
	 * @return
	 */
	public static boolean containsKey(String section,String key) {
		Properties p = (Properties) sections.get(section);
		return p.contains(key);
	}
}